/**
 * Created by showtan on 2018/12/27.
 * task
 */

export default {
  namespace: 'task',
  state: {
    num: 1,
    list_status: -1,
    list: [],
    total: '',
    isLoading: true,
    isLoadMore: false,
    isRefreshing: false,
    backMessage: ''
  },
  subscriptions: { // Subscription 语义是订阅，用于订阅一个数据源，然后根据条件 dispatch 需要的 action。数据源可以是当前的时间、服务器的 websocket 连接、keyboard 输入、geolocation 变化、history 路由变化等等。
    setup({ dispatch }) {
      AppState.addEventListener('change', (appState) => {
        dispatch({ type: "change", payload: { num: 0 } });
      })
    }
  },
  effects: {
    *changeNum({ payload }, { call, put }) {
      console.log('changeNum', payload);
      yield put({
        type: 'updateStates',
        payload: {
          num: payload.num
        }
      })
    },
    *change({ payload }, { call, put }) {
      console.log('change', payload);
      yield put({
        type: 'updateStates',
        payload: {
          num: payload.num
        }
      })
    },
    *taskList({ payload }, { call, put }) {
      // const { data } = yield call(taskList, { countrys: payload.countrys, currentPage: payload.currentPage, showCount: payload.showCount });
      // global.consoleLog && console.log('文章列表', payload, data);
      // if (data && data.returnResult && data.returnResult.code == '00000') {
      yield put({
        type: 'listSuccess',
        payload: {
          list_status: 0,
          // list: data.json,
          // total: data.artcleCount,
          isLoading: payload.isLoading,
          isRefreshing: payload.isRefreshing,
          isLoadMore: payload.isLoadMore,
          currentPage: payload.currentPage
        }
      })
      // } else {
      //     yield put({
      //         type: 'updateStates',
      //         payload: {
      //             list_status: 1,
      //             backMessage: data && data.returnResult ? data.returnResult.messg : '请求失败'
      //         }
      //     })
      // }
    }
  },

  reducers: {
    updateStates(state, action) {
      return { ...state, ...action.payload }
    },
    listSuccess(state, action) {
      let newList = action.payload.isLoadMore ? state.list.concat(action.payload.list) : action.payload.list;
      let isLoadMore = action.payload.total !== newList.length;
      return { ...state, list: newList, currentPage: action.payload.currentPage, total: action.payload.total, isRefreshing: false, isLoading: false, isLoadMore: isLoadMore, list_status: action.payload.list_status }
    }
  }
}